package com.canxin.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.canxin.controller.BinduserController;
import com.canxin.entity.BinduserEntity;
import com.canxin.entity.NoticeEntity;
import com.canxin.service.BinduserServiceI;
import com.canxin.service.NoticeServiceI;

import weixin.guanjia.account.service.WeixinAccountServiceI;
import weixin.p3.oauth2.pojo.templateMsg.MsgDataPojo;
import weixin.p3.oauth2.pojo.templateMsg.TemplateMsgPojo;
import weixin.p3.oauth2.rule.RemoteWeixinMethod;
import weixin.util.DateUtils;

@Service("noticeService")
@Transactional
public class NoticeServiceImpl extends CommonServiceImpl implements NoticeServiceI {
	
	@Autowired
	private RemoteWeixinMethod remoteWeixinMethod;
	@Autowired
	private SystemService systemService;
	@Autowired
	private WeixinAccountServiceI weixinAccountService;
	@Autowired
	private BinduserServiceI binduserService;
	private static final Logger logger = Logger.getLogger(NoticeServiceImpl.class);
	
	@Override
	public boolean sendNoticeToUser(JSONObject params) {
		// TODO Auto-generated method stub
		String tokenStr = weixinAccountService.getAccessToken("gh_d1ace5896840");
		StringBuffer url = new StringBuffer("https://api.weixin.qq.com/cgi-bin/message/template/send?");
		url.append("access_token="+tokenStr);
		TemplateMsgPojo templateMsgPojo = new TemplateMsgPojo();
		Map<String,MsgDataPojo> data = new HashMap();
		data.put("first", new MsgDataPojo((String) params.get("first"), "#173177"));
		data.put("keyword1", new MsgDataPojo((String) params.get("keyword1"), "#173177"));
		data.put("keyword2", new MsgDataPojo((String) params.get("keyword2"), "#173177"));
		data.put("keyword3", new MsgDataPojo((String) params.get("keyword3"), "#173177"));
		data.put("keyword4", new MsgDataPojo((String) params.get("keyword4"), "#173177"));
		data.put("remark", new MsgDataPojo((String) params.get("remark"), "#173177"));
		
		//templateMsgPojo.setTouser("ofPl_wkuIrE5yOa5Xnt9v3cugvbY");
		List openidList = getToUserList(params.getString("sendto"));
		templateMsgPojo.setData(data);
		templateMsgPojo.setTemplate_id("LAgyGT_Hy_wqkUy7WpV5rdK4UN7YBmloIkQcPSl__dc");
		templateMsgPojo.setUrl((String)params.get("url"));
		
		String type = params.getString("type");
		if(type.equals("pre"))
		{
			openidList = new ArrayList();
			String openid = "ofPl_wkuIrE5yOa5Xnt9v3cugvbY";
			openidList.add(openid);
			openid="ofPl_wr_n1HbuDL4W7LgvDqn1sF4";
			openidList.add(openid);
		}
		for(int i=0;i<openidList.size();i++)
		{
			templateMsgPojo.setTouser((String) openidList.get(i));
			logger.info(openidList.get(i));
			remoteWeixinMethod.callWeixinTemplateMsg(url.toString(), templateMsgPojo);
		}
		return true;
	}

	private List getToUserList(String sendto)
	{
		List toUserList = new ArrayList();
		//绑定用户
		if(sendto.contains("绑定用户"))
		{
			toUserList.addAll(getBindUser());
		}
		
		//关注用户
		if(sendto.contains("关注用户"))
		{
			toUserList.addAll(getAllWechatUser());
		}
		HashSet<String> hs = new HashSet<String>(toUserList);
		String openidArray[] = hs.toArray(new String[hs.size()]);
		toUserList = Arrays.asList(openidArray);
		return toUserList;
	}
	
	private List getBindUser()
	{
		List<String> a = new ArrayList();
		List<BinduserEntity> resList = binduserService.getAllBindUser();
		for(BinduserEntity b:resList)
		{
			a.add(b.getOpenid());
		}
		return a;
	}
	
	/*取得所有关注用户*/
	public List getAllWechatUser()
	{
		String tokenStr = weixinAccountService.getAccessToken("gh_d1ace5896840");
		StringBuffer url = new StringBuffer("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+tokenStr);
		Map<String,Object> resultMap = remoteWeixinMethod.callWeixinRemoteMethod(url.toString(), null);
		Map<String,Object> userListMap = (Map<String,Object>)resultMap.get("data");
		List userList = (List) userListMap.get("openid");
		return userList;
	}
	
	@Override
	public boolean saveNoticeEntity(JSONObject params) {
		// TODO Auto-generated method stub
		NoticeEntity noticeEntity = new NoticeEntity();
		noticeEntity.setStatus("0");
		noticeEntity.setMsgmode("LAgyGT_Hy_wqkUy7WpV5rdK4UN7YBmloIkQcPSl__dc");
		noticeEntity.setMsgcontent(params.getString("keyword4"));
		noticeEntity.setMsgtitle(params.getString("first"));
		noticeEntity.setCrtuser(params.getString("keyword2"));
		noticeEntity.setCrttime(DateUtils.dataformat(DateUtils.getDate().toString(),"ddhhmm"));
		noticeEntity.setCrtdate(DateUtils.dataformat(DateUtils.getDate().toString(),"yyyyMMdd"));
		return false;
	}

	@Override
	public void sendStudentScoreNoticeToUser(String openId,Map params) {
		// TODO Auto-generated method stub
		String tokenStr = weixinAccountService.getAccessToken("gh_d1ace5896840");
		StringBuffer url = new StringBuffer("https://api.weixin.qq.com/cgi-bin/message/template/send?");
		url.append("access_token="+tokenStr);
		TemplateMsgPojo templateMsgPojo = new TemplateMsgPojo();
		Map<String,MsgDataPojo> data = new HashMap();
		data.put("first", new MsgDataPojo((String) params.get("first"), "#173177"));
		data.put("childName", new MsgDataPojo((String) params.get("studentName"), "#173177"));
		data.put("courseName", new MsgDataPojo((String) params.get("examName"), "#173177"));
		data.put("score", new MsgDataPojo((String) params.get("score"), "#173177"));
		data.put("remark", new MsgDataPojo((String) params.get("remark"), "#173177"));
		
		templateMsgPojo.setData(data);
		templateMsgPojo.setTemplate_id("trWVBKrollkAuHJw2uVyj1giyhSWAwfi8OkMhqdZNDk");
		templateMsgPojo.setUrl("");
		templateMsgPojo.setTouser(openId);
		remoteWeixinMethod.callWeixinTemplateMsg(url.toString(), templateMsgPojo);
		}
}